<?php
namespace Modules\Chip\Http\Controllers\Client\V1;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;

use \Modules\Chip\Entities\Chip;
use \Modules\Chip\Entities\ChipAsset;
use \Modules\Box\Entities\BoxSku;

use Validator;
use ThrowException;
use DB;
use Auth;

class CoverChipController extends Controller
{
    // 确认兑换
    public function store(Request $req)
    {
        $rule = [
            'sku_id' => ['required']
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest();

        $user = Auth::requireLoginUser();

        $sku = BoxSku::getEntity([
            'id' => $req->sku_id,
            'with' => ['chip']
        ]);

        if (!$sku->chip) {
            ThrowException::Conflict('暂未查询到可兑换的碎片~');
        }

        $chip = $sku->chip;

        // 开始兑换
        // 需要集齐的sku数量
        $needSkuTotal = $sku->chip_need_sku_total;
        $chipTotal = $sku->chip_total;

        if ($chip->stock < $chipTotal) {
            ThrowException::Conflict('兑换失败，库存不足~');
        }

        $orders = $user->orders()->status('pending')->hasSku($sku)->take($needSkuTotal)->get();

        if ($orders->count() < $needSkuTotal) {
            ThrowException::Conflict('兑换失败，您目前只集有' . $orders->count() . '款' . $sku->title);
        }

        DB::beginTransaction();
        $chipAsset = ChipAsset::where('user_id', $user->id)->where('chip_id', $chip->id)->first();
        if (!$chipAsset) {
            $chipAsset = ChipAsset::create([
                'user_id' => $user->id,
                'chip_id' => $chip->id
            ]);
        }

        $chipAsset->in($chipTotal, '盲盒兑换');
        $chip->update([
            'cover_total' => $chip->cover_total + $chipTotal,
            'stock' => $chip->stock - $chipTotal
        ]);

        foreach ($orders as $order) {
            // 标记为已兑换
            $order->coverToChip();
        }

        DB::commit();

        return [
        ];
    }

    // 兑换详情
    public function show(Request $req)
    {
        $rule = [
            'sku_id' => ['required']
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest();


        $sku = BoxSku::getEntity([
            'id' => $req->sku_id,
            'with' => ['chip']
        ]);

        if (!$sku->chip) {
            ThrowException::Conflict('暂未查询到可兑换的碎片~');
        }

        $info = [];

        $info['sku'] = $sku->getInfo([
            'id',
            'uuid',
            'title',
            'thumb',
        ]);

        $info['chip'] = $sku->chip->getInfo([
            'title',
            'icon',
        ]);

        $info['need_sku'] = $sku->chip_need_sku_total;
        $info['chip_total'] = $sku->chip_total;

        return $info;
    }
}